package com.badibadi.mytools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.widget.TextView;


/** 
 * 加载网络图片异步类 (这里是用于在TextView上面显示html的表情)
 * @author Susie 
 */  
public class AsyncLoadNetworkPic extends AsyncTask<String, Integer, Void>{  

	 TextView mTvThree;
	 String source;
	 ImageGetter mImageGetter;
	 public AsyncLoadNetworkPic(String source,TextView mTvThree,ImageGetter mImageGetter)
	 {
		this.mTvThree=mTvThree;
		this.source=source;
		this.mImageGetter=mImageGetter;
	 }
	 
    @Override  
    protected Void doInBackground(String... params) {  
        // 加载网络图片  
        loadNetPic(params);  
        return null;  
    }  
      
    @Override  
    protected void onPostExecute(Void result) {  
        super.onPostExecute(result);  
        // 当执行完成后再次为其设置一次  
        mTvThree.setText(Html.fromHtml(source, mImageGetter, null));  
    }  
    /**加载网络图片*/  
    private void loadNetPic(String... params) {  
        String path = params[0];
          
        File file = new File(Environment.getExternalStorageDirectory(), "badibadi");  
          
        InputStream in = null;  
          
        FileOutputStream out = null;  
          
        try {  
            URL url = new URL(path);  
              
            HttpURLConnection connUrl = (HttpURLConnection) url.openConnection();  
              
            connUrl.setConnectTimeout(5000);  
              
            connUrl.setRequestMethod("GET");  
              
            if(connUrl.getResponseCode() == 200) {  
                  
                in = connUrl.getInputStream();  
                  
                out = new FileOutputStream(file);  
                  
                byte[] buffer = new byte[1024];  
                  
                int len;  
                  
                while((len = in.read(buffer))!= -1){  
                    out.write(buffer, 0, len);  
                }  
            } else {  
//                   
            }  
        } catch (Exception e) {  
                 
        } finally {  
              
            if(in != null) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                         
                }  
            }  
            if(out != null) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                         
                }  
            }  
        }  
    }  
}  